package de.hpi.generator.model;

import de.hpi.generator.config.DatabaseModel;
import de.hpi.generator.config.NotExistsException;
import de.hpi.generator.config.TableModel;
import de.hpi.generator.helpers.TableDiagnostic;

public class Database {

    private String aName;

    public String getName() {
        return aName;
    }
    private TablesCollection aTables = new TablesCollection();    
    private String aWorkingDirectory = null;

    public TablesCollection getTables() {
        return aTables;
    }

    public String getWorkingDirectoryPath() {
        return aWorkingDirectory;
    }

    public Database(DatabaseModel aDatabaseModel, String aOutputPath) {
        this.aName = aDatabaseModel.name;
        this.aWorkingDirectory = aOutputPath + "\\" + this.getName();
    }

    public ColumnsCollection getAllColumns() {
        ColumnsCollection result = new ColumnsCollection(new Table(new TableModel("_AllColumns_", -1), this));
        for (Table aTable : aTables) {
            result.addAll(aTable.getColumns());
        }
        return result;
    }

    public Column findColumnByPath(String aColumnPath) throws NotExistsException {
        String[] aColumnPathArray = aColumnPath.split(":");
        Table aTable = getTables().findTableByName(aColumnPathArray[0]);
        Column aColumn = aTable.getColumns().findColumnByName(aColumnPathArray[1]);
        return aColumn;

    }

    @Override
    public String toString() {

        String result = String.format("{name: %s, \n tables:[ \n", getName());
        String aTablesString = "";
        String aCompositeInclusionDependencyString = "";
        for (Table aTable : getTables()) {
            aTablesString += "\t" + aTable.toString();
        }

        return result + aTablesString + "]\n " + aCompositeInclusionDependencyString + "\n}\n";
    }

    protected void generateBaseColumnValues() throws Exception {
        for (Column aColumn : this.getAllColumns()) {
            if (aColumn.isValuesNotGenerated()) {
                aColumn.generateBaseColumnValues();
            }
        }
    }

    protected void balanceColumnsInTables() throws Exception {
        for (Table aTable : aTables) { 
            long start = System.currentTimeMillis();
            System.out.println("Balancing columns for " + aTable.getName());
            aTable.balanceColumnsValues();
            System.out.println("The balancing took: " + ((System.currentTimeMillis()-start)/1000) + "sec");
        }
    }

    public void generateData() throws Exception {
        generateBaseColumnValues();
        balanceColumnsInTables();
    }
}
